import time
from bitfinex.client import Client
from bitfinex.client import TradeClient
import config
from lib.bmobHelper import BmobHelper

client = Client()
tradeClient = TradeClient(config.KEY, config.SECRET)
record = BmobHelper()

print('Start:')
while True:
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
    print(datetime)
    
    deposit_available = tradeClient.balances()
    frr = client.frr('btc')
    recent_rate = client.lendbook('btc')
    record.record_op('frr', int(frr*0.85*100)/100)
    record.record_op('recent_rate', int(recent_rate*0.85*100)/100)

    if deposit_available > 0.05:
        rate = int((recent_rate + (frr-recent_rate)*config.RATIO) * 100) / 100
        record.record_op('offer_rate', rate*0.85)

        resp = tradeClient.place_offer('btc', str(deposit_available), str(rate), 2, 'lend')
        print("Lend amount: %s" % (deposit_available))

        isSucccess = True
        for key in resp.keys():
            if key == "message":
                isSucccess = False
        
        if isSucccess:
            print("Lend successfully: amount: %s, rate %s%s" % (resp['original_amount'], resp['rate'], '%'))
        else:
            print("Lend failed: message: %s" % (resp["message"]))

    else:
        print("Not enough BTC")
    
    # 记录利润
    record.record_op('profit', int(tradeClient.history_profit('btc')*1000000)/1000000)

    print("--------------------------")

    time.sleep(config.TickInterval)